from flask import Blueprint,request,jsonify
from model import db,college,User,classInfo,statuscourse,course,UserInfo,redisclient
from sqlalchemy.exc import IntegrityError
from sqlalchemy import func
import json
import re
ad=Blueprint('ad',__name__,url_prefix='/api/admin')
@ad.route('/school',methods=['GET', 'POST','DELETE'])
def collages():
    if request.method == 'GET':
       findlist=college.query.all()
       data=[]
      
       for i in findlist:
           if i.major is None:
          
            data.append({'id':i.id,'timestamp':i.timestamp,'collegename':i.collegename})
       return jsonify(code=200,data=data)
    elif request.method=='POST':
        name=request.get_json().get('name')
        if name is None:
            return jsonify(code=400)
        if college.query.filter_by(collegename=name).first() is not None:
            return jsonify(code=400,messgae="当前学院已经存在")
        db.session.add(college(collegename=name))
        db.session.commit()
        return jsonify(code=200)
    elif request.method == 'DELETE':
        try:
            data=request.get_json()
         
            collegeid=data['collegeid']
            collegetype=data.get('collegetype')
            
        except KeyError:
            return jsonify(code=400,message='参数错误')
        findname=college.query.filter_by(id=collegeid)
        if collegetype is None:
            findname=findname.first()
            if findname is None:
                return jsonify(code=400,message='数据不存在')
            college.query.filter_by(collegename=findname.collegename).delete()
            db.session.commit()
            return jsonify(code=200,message='删除数据成功')
        findname.delete()
        db.session.commit()
        return jsonify(code=200,message='删除专业成功')
        
        
@ad.route('/major',methods=['GET', 'POST','DELETE'])
def major():
    if request.method == 'GET':
       findlist=college.query.all()
       data=[]
       for i in findlist:
           if i.major is not None:
              data.append({'id':i.id,'timestamp':i.timestamp,'collegename':i.collegename,'major':i.major})
       return jsonify(code=200,data=data)
    elif request.method=='POST':
        major=request.get_json().get('major')
        collegeid=request.get_json().get('collegeid')
        if major is None or collegeid is None:
            return jsonify(code=400,message='参数错误')
        findcoll=college.query.filter_by(id=int(collegeid)).first()
        if findcoll is None:
            return jsonify(code=400,message='当前学院不存在')
        try:
            db.session.add(college(major=major,collegename=findcoll.collegename))
            db.session.commit()
            return jsonify(code=200,message='添加数据成功')
        except IntegrityError:
            db.session.rollback()
            return jsonify(code=400,message='数据已存在')
@ad.route('/teacher',methods=['POST','GET','DELETE','PUT'])
def teacher():
    if request.method=='GET':
        findlist=User.query.filter_by(role='teacher').all()
        if findlist is None:
            return jsonify(code=200,data=[])
        data=[]
        UserData=[]
        for i in findlist:
            data.append({'id':i.id,'username':i.username,'password':i.password})
            UserData.append(i.username)
        finduserinfo=UserInfo.query.filter(UserInfo.username.in_(UserData)).all()
        
        index=0
        for i in data:
            for j in finduserinfo:
                if j.username == i['username']:
                    i['age']=j.age
                    i['gender']='男' if j.gender else "女"
                    i['phone']=j.phone
            data[index]=i
            index+=1   
        return jsonify(code=200,data=data)      
    elif request.method=='POST':
        data=request.get_json()
        try:
            teacherName=data['teacherName']
            age=data['age']
            password=data['password']
            phone=data['phone']
            gender=True if data['gender']=='男' else False
        except KeyError:
            return jsonify(code=400,message='参数错误')
        res=re.match('[a-zA-Z0-9_-]{10,20}',password)
        if not res:
            return jsonify(code=400,message='密码格式错误')
        if not 0<int(age)<120:
            return jsonify(code=400,message='年龄输入异常')
        try:
           
            addlist=[User(username=teacherName,password=password,role='teacher'),UserInfo(username=teacherName,age=age,gender=gender,phone=phone)]
            db.session.add_all(addlist)
            db.session.commit()
            return jsonify(code=200,message='添加成功')
        except IntegrityError:
            return jsonify(code=400,message='用户名重复')
    elif request.method=='DELETE':
        userid=request.get_json().get('userid')
        if userid is None:
            return jsonify(code=400,message='参数错误')
        User.query.filter_by(id=userid).delete()
        db.session.commit()
        return jsonify(code=200,message='删除成功')
    elif request.method=='PUT':
        data=request.get_json()
        try:
            phone=data['phone']
            age=data['age']
            password=data['password']
            gender=data['gender']
            userid=data['id']
        except KeyError:
            return jsonify(code=400,message='参数错误')
        res=re.match('[a-zA-Z0-9_-]{10,20}',password)
        if not res:
            return jsonify(code=400,message='密码格式错误')
        finduser=User.query.filter_by(id=userid).first()
        if finduser is None:
            return jsonify(code=400,message='用户不存在')
        finduser.password=password
        UserInfo.query.filter_by(username=finduser.username).update({'phone':phone,'age':age,'gender':True if gender=='男' else False})
        db.session.commit()
        return jsonify(code=200,message='修改成功')
@ad.route('/students',methods=['GET','POST','DELETE','PUT'])
def students():
    if request.method=='GET':
        finduser=User.query.filter_by(role='user').all()
        if finduser is None:
            return jsonify(code=200,data=[])
        data=[]
        useriddata=[]
        usernamedata=[]
        for i in finduser:
            data.append({"id":i.id,'username':i.username,'password':i.password})
            useriddata.append(i.id)
            usernamedata.append(i.username)
        finduserinfo=UserInfo.query.filter(UserInfo.username.in_(usernamedata)).all()
        findclass=classInfo.query.filter(classInfo.userid.in_(useriddata)).all()
        findcollege=college.query.filter(college.id.in_(useriddata)).all()
        majordata=[]
      
        for i in range(0,len(finduserinfo)):
            print(finduserinfo[i].username)
            print(finduser[i].username)
            for j in finduser:

                if finduserinfo[i].username==j.username:

                    data[i]['age']=finduserinfo[i].age
                    data[i]['gender']="男" if finduserinfo[i].gender else "女"
            if  findclass!=[] and findclass[i].userid==finduser[i].id:
                data[i]['classname']=findclass[i].classname
                data[i]['major']=findclass[i].major
                majordata.append(findclass[i].major)
        findcollege=college.query.filter(college.major.in_(majordata)).all()
        index=0
        for i in data:
            for j in findcollege:
                if i['major']==j.major:
                    i['college']=j.collegename
            data[index]=i
            index+=1
        return jsonify(code=200,data=data)
    elif request.method == 'POST':
        print('aaa')
        data=request.get_json()
        try:
            username=data['username']
           
            age=data['age']
            gender=data['gender']
            classname=data['classname']
            collegename=data['college']
            major=data['major']
        except KeyError:
            return jsonify(code=400,message='缺少必要参数')
        findmajor=college.query.filter_by(collegename=collegename,major=major).first()
        if findmajor is None:
            return jsonify(code=400,message='学院或专业不存在')
        findclass=classInfo.query.filter_by(classname=classname,major=major).first()
        if findclass is None:
            return jsonify(code=400,message='班级不存在')
        try:
            db.session.add(User(username=username))
            db.session.commit()
        except IntegrityError:
            db.session.rollback()
            return jsonify(code=400,message='用户名已存在')
        userid=User.query.filter_by(username=username)
        adlist=[UserInfo(username=username,age=age,gender=True if gender=='男' else False),classInfo(userid=userid.first().id,classname=classname,major=major)]
        try:
            db.session.add_all(adlist)
            db.session.commit()
            return jsonify(code=200,message='添加成功')
        except IntegrityError:
            
            db.session.rollback()
            userid.delete()
            db.session.commit()
            return jsonify(code=400,message='专业不存在')
    elif request.method=='DELETE':
        valueid=request.get_json().get('id')
        if valueid is None:
            return jsonify(code=400,message='id不能为空')
        finduser=User.query.filter_by(id=valueid).delete()
        db.session.commit()
        return {'code':200}
    elif request.method=='PUT':
        data=request.get_json()
        try:
            age=data['age']
            password=data['password']
            userid=data['userid']
        except KeyError:
            return jsonify(code=400,message='参数错误')
        res=re.match('^[0-9A-Za-z]{10,20}$',password)
        if not password:
            return jsonify(code=400,message='密码格式错误')
        finduser=User.query.filter_by(id=userid).first()
        if finduser is None:
            return jsonify(code=400,message='用户不存在')
        finduser.password=password
        finduserinfo=UserInfo.query.filter_by(username=finduser.username).first()
        finduserinfo.age=age
        db.session.commit()
        return jsonify(code=200)
        


@ad.route('/classinfo',methods=['GET', 'POST','PUT','DELETE'])
def classInfoful():
    if request.method == 'GET':
       
        classname=request.args.get('classname',type=str)
        if classname is None:
            findclass=classInfo.query.all()
            data=[]
            for i in findclass:
                if i.userid is None:
                    data.append({"id":i.id,'classname':i.classname,'timestamp':i.timestamp,'major':i.major})  
            return jsonify(code=200,data=data)
  

        results = classInfo.query.filter(func.lower(classInfo.classname).like(f"%{classname.lower()}%")).all()
        data=[]
        for i in results:
            if i.userid is None:
                data.append({"id":i.id,'classname':i.classname,'timestamp':i.timestamp,'major':i.major})  
        return jsonify(code=200,data=data)
    elif request.method=='POST':
        data=request.get_json()
        try:
            classname=data['classname']
            major=data['major']
            collegename=data['collegename']
        except KeyError:
            return jsonify(code=400,message='参数错误')
        findcollege=college.query.filter_by(collegename=collegename).all()
        if findcollege is None:
            return jsonify(code=400,message='学院不存在')
        keysdata=[]
        for key in findcollege:
            keysdata.append(key.major)
        
        findclass=classInfo.query.filter(classInfo.major.in_(keysdata)).all()
        #学院下所有的班级
       
        for j in findclass:
            if j.classname==classname:
                return jsonify(code=400,message='班级已存在')
        
        try:
            db.session.add(classInfo(classname=classname,major=major))
            db.session.commit()
            return jsonify(code=200,message='添加成功')
        except IntegrityError:
            return jsonify(code=400,message='专业不存在')
    elif request.method=='PUT':
        data=request.get_json()
        try:
            collegename=data['collegename']
            classname=data['classname']
            classid=data['id']
        except KeyError:
            return jsonify(code=400,message='参数错误')
        findcollege=college.query.filter_by(collegename=collegename).all()
        if findcollege is None:
            return jsonify(code=400,message='学院不存在')
        keysdata=[]
        for key in findcollege:
            keysdata.append(key.major)
        
        findclass=classInfo.query.filter(classInfo.major.in_(keysdata)).all()
        for j in findclass:
            if j.classname==classname:
                return jsonify(code=400,message='班级已存在')
        findclass=classInfo.query.filter_by(id=classid).first()
        if findclass is None:
            return jsonify(code=400,message='查无此班级')
        findclass.classname=classname
        db.session.commit()
        return jsonify(code=200)
    elif request.method == 'DELETE':
        id=request.args.get('id',type=int)
        if id is None:
            return jsonify(code=400,message='参数错误')
        findclass=classInfo.query.filter_by(id=id).first().classname
        findclass=classInfo.query.filter_by(classname=findclass)
        useriddata=[]
        for i in findclass.all():
            useriddata.append(i.userid)
        User.query.filter(User.id.in_(useriddata)).delete()
        findclass.delete()
        db.session.commit()
        return jsonify(code=200)
    

@ad.route('/course',methods=['GET','POST','DELETE'])
def coursetable():
    if request.method == 'GET':
        coursename=request.args.get('name')
        data=[]
        classiddata=[]
        if coursename is None:
            findcourse=course.query.all()
          
            for i in findcourse:

                data.append({'classid':i.classid,'id':i.id,'coursename':i.coursename,'timestamp':i.timestamp,'messages':i.messages})
                classiddata.append(i.classid)
            findclasslist=classInfo.query.filter(classInfo.id.in_(classiddata)).all()  
            if findclasslist==[]:
                return jsonify(code=200,data=data)
            print("数组:",classiddata)
            print('data:',data)
            index=0
            for i in data:
                for j in findclasslist:
                    if i['classid']==j.id:        
                        data[index]['classname']=j.classname
                        data[index]['major']=j.major
                index+=1
            return jsonify(code=200,data=data)
        results = course.query.filter(func.lower(course.coursename).like(f"%{coursename.lower()}%")).all()
        classiddata=[]
        for i in results:
            classiddata.append(i.classid)
            data.append({'classid':i.classid,'id':i.id,'coursename':i.coursename,'timestamp':i.timestamp,'messages':i.messages})
        findclasslist=classInfo.query.filter(classInfo.id.in_(classiddata)).all()  
        if findclasslist==[]:
            return jsonify(code=200,data=data)
        index=0
        for i in data:
            for j in findclasslist:
                if i['classid']==j.id:        
                    data[index]['classname']=j.classname
                    data[index]['major']=j.major
            index+=1
        return jsonify(code=200,data=data)
    elif request.method == 'POST':
        data=request.get_json()
        try:
            coursename=data['course']
            collegename=data['collegename']
            classname=data['classname']
            username=data['teacher']
            messages=data['messages']
        except KeyError:
            return jsonify(code=400,message='参数错误')
        findcollege=college.query.filter_by(collegename=collegename).all()
        majorlist=[]
        for i in findcollege:
            majorlist.append(i.major)
        boolvalue=True

        for j in classInfo.query.filter(classInfo.major.in_(majorlist)).all():
            if j.classname==classname and j.userid==None:
                boolvalue=False
                classid=j.id
                break
        if boolvalue:
            return jsonify(code=400,message='班级不存在')
        if course.query.filter_by(classid=classid,coursename=coursename).first() is not None:
            return jsonify(code=400,message='课程已经存在')
        try:
            db.session.add(course(classid=classid,coursename=coursename,teacher=username,messages=messages))
            db.session.commit()
            return jsonify(code=200)
        except IntegrityError:
            db.session.rollback()
            return jsonify(code=400,message='用户名不存在')
    elif request.method=='DELETE':
        valueid=request.args.get('valueid')
        if valueid is None:
            return jsonify(code=400,message='id不存在')
        course.query.filter_by(id=valueid).delete()
        statuscourse.query.filter_by(courseid=valueid).delete()
        db.session.commit()
        return jsonify(code=200,message='删除成功')
@ad.route('/studentssearch',methods=['POST'])
def searchstudents():
      if request.method=='POST':
          data=request.get_json()
          boolvalue=True
          try:
            studentname=data.get('username')
            if searchstudents!=None:
                boolvalue=False
            collegename=data['collegename']
            classname=data['classname']
          except KeyError:
              return jsonify(code=400,message='参数错误')
          data=redisclient.get(classname+collegename)
          if data is not None:
              data=json.loads(data)
            
              if not boolvalue:
                    a=0
                    for j in data:
                        if j['username']==studentname:
                            a=1
                            return jsonify(code=200,data=[j,])
                    if a==0:
                        return jsonify(code=200,data=[])
              return jsonify(code=200,data=data)
          majorlist=[]
          for i in college.query.filter_by(collegename=collegename).all():
              if i.major==None:
                  continue
              majorlist.append(i.major)
          data=[]
          findclass=classInfo.query.filter(classInfo.major.in_(majorlist),classInfo.userid!=None,classInfo.classname==classname).all()
          useriddata=[]
          for i in findclass:
              useriddata.append(i.userid)
              data.append({'id':i.userid,'college':collegename,'classname':i.classname,'major':i.major})
          finduser=User.query.filter(User.id.in_(useriddata)).all()
          usernamedata=[]
          for i in range(0,len(data)):
              usernamedata.append(finduser[i].username)
              data[i]['username']=finduser[i].username
              data[i]['password']=finduser[i].password
          finduserinfolist=UserInfo.query.filter(UserInfo.username.in_(usernamedata)).all()
          for i in range(0,len(finduserinfolist)):
              data[i]['age']=finduserinfolist[i].age
              data[i]['gender']="男" if finduserinfolist[i].gender else "女"
          redisclient.setex(classname+collegename,120,json.dumps(data))
          if not boolvalue:
                a=0
                for j in data:
                    
                    if j['username']==studentname:
                        a=1
                        return jsonify(code=200,data=[j,])
                if a==0:
                    return jsonify(code=200,data=[])
          return jsonify(code=200,data=data)
             


           
          

      

        
            